<template>
  <scroll-view ref="scrollview" class="comments-container" scroll-y :scroll-x="false" @scroll="handleScroll"
    :show-scrollbar="false">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="gotoArticle">
        <uni-icons type="closeempty" size="30"></uni-icons>
      </view>
      <view class="navbar-center">
        <text class="navbar-title">{{ articleTitle }}</text>
      </view>
      <view class="navbar-right">
        <uni-icons type="more-filled" size="30"></uni-icons>
      </view>
    </view>
    <view class="comment-list">
      <view class="comment-item" v-for="(comment, index) in comments" :key="index">
        <view class="avatar-username">
          <view class="avatar">
            <image :src="comment.user.avatar" class="avatar-img" />
          </view>
          <view class="username">{{ comment.user.nickname }}</view>
        </view>
        <view class="content">
          <view class="text-container" :id="'content-' + comment.id" :data-need-expand="contentHeights[comment.id]"
            @click="showFullContent(comment.id, index)">
            {{ comment.content }}
          </view>
          <text class="expand-btn" @click="toggleExpand(comment.id)" v-if="contentHeights[comment.id]">全文</text>
        </view>
        <view class="time-stats">
          <view class="time">{{ timeAgo(comment.created_at) }}</view>
          <view class="stats">
            <uni-icons type="chat" size="16"></uni-icons>
            <uni-icons type="heart" size="16">{{ comment.like_count ? comment.like_count : '' }}</uni-icons>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>

  <!-- 弹出评论轮播 -->

  <uni-popup class="popup" ref="popup" :is-mask-click="false" type="center" border-radius="10px 10px 10px 10px"
    @change="onPopupChange" background-color="transparent" :style="{ height: popupHeight + 'px' }">
    <swiper class="swiper" :current="currentIndex" :style="{ height: swiperHeight + 'px' }">
      <swiper-item v-for="comment in comments" :key="comment.id" class="swiper-item">
        <view class="comment-container">
          <view class="avatar-username">
            <image :src="comment.user.avatar" class="avatar-img" />
            <view class="username">
              <view>{{ comment.user.nickname }}</view>
              <view> {{ timeAgo(comment.created_at) }} </view>
              <uni-icons type="more-filled" size="30"></uni-icons>
            </view>
          </view>
          <view class="comment-content">
            <text class="content"> {{ comment.content }}</text>
          </view>
          <view class="stats">
            <uni-icons type="chat" size="16"></uni-icons>
            <uni-icons type="heart" size="16">{{ comment.like_count ? comment.like_count : '' }}</uni-icons>
          </view>
          <view class="reply"></view>
        </view>
      </swiper-item>
    </swiper>

  </uni-popup>
</template>
<script setup>
import { timeAgo } from "@/util/index.js"
import { ref, onMounted, nextTick, computed } from "vue";
import { onLoad } from '@dcloudio/uni-app'
import { getCommentList } from "@/api/index.js"
// 获取设备信息
const systemInfo = uni.getSystemInfoSync();
const windowHeight = systemInfo.windowHeight; // 视口高度
const statusBarHeight = systemInfo.statusBarHeight || 15; // 状态栏高度
const screenHeight = systemInfo.screenHeight; // 屏幕高度

const popupHeight = computed(() => {
  return (screenHeight - statusBarHeight - 60) * 1  // 确保纯数字
})
const swiperHeight = computed(() => popupHeight.value)


// 控制导航栏的显示状态
const isNavVisible = ref(false);
// 引用 DOM 元素
const scrollview = ref(null);
const comments = ref([])
const articleId = ref(0)
const articleTitle = ref('')
// 新增展开状态管理
const expandedComments = ref({});

const currentIndex = ref(0)


const toggleExpand = (commentId) => {
  expandedComments.value[commentId] = !expandedComments.value[commentId];
};
onLoad((options) => {
  articleId.value = options.articleId;
  articleTitle.value = options.articleTitle;
})
onMounted(async () => {
  // 获取评论数据
  uni.showLoading({ title: '加载中...', mask: true });
  const res = await getCommentList(articleId.value)
  comments.value = res
  res.forEach(comment => {
    checkContentHeight(comment)
  })
  uni.hideLoading();
})
// 防抖函数
const debounce = (func, delay) => {
  let timer = null;  // 明确初始化
  return function (...args) {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;  // 清除引用
    }, delay);
  };
};
// 滚动事件处理函数
const handleScroll = debounce((event) => {
  const scrollTop = event.detail?.scrollTop || 0; // 获取滚动位置
  // console.log('当前滚动位置:', scrollTop);
  // 控制 custom-navbar 的显示状态
  isNavVisible.value = scrollTop > 30;
  // 获取 article-content 的高度
  uni.createSelectorQuery().select('.article-content').boundingClientRect((contentRect) => {
    if (!contentRect) {
      // console.error('无法获取文章内容信息');
      return;
    }
    const contentHeight = contentRect.height; // 文章内容的高度
    const containerHeight = windowHeight; // 容器可见高度
    const scrollBottom = scrollTop + containerHeight; // 当前滚动底部位置
    // console.log('文章内容高度:', contentHeight);
    // console.log('容器可见高度:', containerHeight);
    // console.log('滚动底部位置:', scrollBottom);
    // 判断是否滚动到 article-content 的底部
    if (scrollBottom >= contentHeight && !isInteractionVisible.value) {
      // console.log('滚动到底部，显示 interaction-buttons');
      isInteractionVisible.value = true; // 显示按钮
    } else if (scrollBottom < contentHeight && isInteractionVisible.value) {
      // console.log('未滚动到底部，隐藏 interaction-buttons');
      isInteractionVisible.value = false; // 隐藏按钮
    }
  }).exec();
}, 100);
const gotoArticle = () => {
  // uni.navigateTo({
  //   url: `/pages/article/article?articleId=${articleId.value}`
  // })
  uni.navigateBack()
}
const contentHeights = ref({});
const checkContentHeight = async (comment) => {
  await nextTick();
  uni.createSelectorQuery().select(`#content-${comment.id}`).boundingClientRect(res => {
    const lineHeight = 18; // 根据实际行高调整（px单位）
    const maxHeight = lineHeight * 8; // 8行最大高度
    contentHeights.value[comment.id] = res.height > maxHeight;
  }).exec();
};
const swiper = ref(null)
const popup = ref(null)
//  以 swipe方式  显示评论全文
const showFullContent = async (commentId, index) => {

  currentIndex.value = index
  await nextTick();
  popup.value.open()
};
</script>
<style lang="scss" scoped>
.comments-container {
  background-color: #e6f7ef;
  position: relative;
  padding: 30px 20px 0 20px;
  /* height: calc(100vh - 60px - env(safe-area-inset-top, 20px)); */
  margin-top: calc(v-bind('statusBarHeight + "px"'));
  overflow-y: auto;
  box-sizing: border-box;
  scrollbar-width: none;
  -ms-overflow-style: none;
  padding-bottom: 10px;

  .custom-navbar {
    transform: translateY(0);
    background-color: rgba(255, 255, 255, 0.9);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    top: 0;
    position: fixed;
    left: 0;
    right: 0;
    height: calc(60px + v-bind('statusBarHeight + "px"'));

    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    transition: transform 0.3s ease-in-out;
    z-index: 1000;

    .navbar-left {
      display: flex;
      align-items: center;
      height: 30px;
    }

    .navbar-title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      height: 30px;
    }

    .navbar-right {
      display: flex;
      align-items: center;
      height: 30px;
    }
  }

  .comment-list {
    margin-top: 60px;

    .comment-item {
      display: flex;
      flex-direction: column;
      background-color: #fff;
      border: 1px solid #fff;
      margin-bottom: 10px;
      border-radius: 10px;
      padding: 10px;

      .avatar-username {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .avatar {
          .avatar-img {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            overflow: hidden;
          }
        }

        .username {
          margin-left: 10px;
          font-size: 14px;
          color: #333;
        }
      }

      .content {
        font-size: 15px;
        line-height: 1.7;
        margin-bottom: 10px;
        position: relative;

        .text-container {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          overflow: hidden;
          position: relative;
          -webkit-line-clamp: 8;
          font-size: 14px;

          &::after {
            background: none;

          }

          &[data-need-expand="true"] {
            -webkit-line-clamp: 8;
            /* 保持截断效果 */
          }
        }

        .expand-btn {
          position: static;
          display: block;
          margin-top: 15px;
          color: #a0700ac9;
          font-size: 14px;
          text-align: left;
        }
      }

      .time-stats {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;

        .time {
          font-size: 12px;
        }

        .stats {
          font-size: 12px;

          .uniui-heart {
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.popup {
  z-index: 1;
  width: calc(100vw - 40px);
  /* height: calc(100vh - calc(70px + v-bind('statusBarHeight + "px"'))); */
  display: flex;
  flex-direction: column;

  /* margin-top: calc(60px + v-bind('statusBarHeight + "px"')) !important; */
  ::v-deep.uni-popup__wrapper.center {

    top: calc(v-bind('statusBarHeight') * 1px + 60px) !important;
    height: calc(100vh - v-bind('statusBarHeight') * 1px - 60px) !important;
    width: calc(100vw - 40px);

    .swiper {
      background-color: #fff;
      width: calc(100vw - 40px);
      /* height: calc(100vh - 60px); */
      /* height: v-bind(swiperHeight);*/



      .swiper-item {
        width: calc(100vw - 40px) !important;
        height: calc(100vh - 60px) !important;

        .comment-container {
          // height: calc(100vh - 60px);
          /* 减去导航栏和状态栏高度 */
          padding: 20px;
          background: #fff;
          border-radius: 10px;

          .avatar-username {
            .avatar-img {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              overflow: hidden;
            }
          }
        }
      }
    }

  }





}
</style>